<template>
  <div>
    <search :form-inline="role" :rows="rows" @search="getRoleList" @reset="reset"></search>
    <!--       卡片区域-->
      <table-list :page="role" :columns="columns" :table-data="roleList" @addBtn="addRole" @edit="editRole"
                  @pageChange="pageChange" @delete="delRole" @roleUser="RoleUsers" @jurisdiction="jurisdiction"
                  @menu="jurisMenu" :disabled="this.common.roleShow">
      </table-list>
    <!--        添加/修改弹出框-->
    <el-drawer v-model="roleDialogVisible"  size="30%"
               :title="(this.role.code == null||this.role.code=='')?'添加':'修改'">
      <el-form :model="roleForm"  label-width="100px" :rules="rules"
               ref="roleForm" >
        <el-form-item label="代码：" prop="code">
          <el-input v-model="roleForm.code" :disabled="disable"></el-input>
        </el-form-item>
        <el-form-item label="角色名称：" prop="name">
          <el-input v-model="roleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="discribe">
          <el-input v-model="roleForm.discribe"></el-input>
        </el-form-item>
        <el-button @click="roleDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="roleSumbit('roleForm')">确定</el-button>
      </el-form>
    </el-drawer>
    <!--        权限信息弹出框-->
      <drawer-tree :title="jurisdictionTitle" :drawer="jurisdictionDialog" :data="roleJurisdiction" :props="jurisdictionProps"
                   :default-checked-keys="roleTree" treeRef="treeRef" @treeBtn="treeBtn">
      </drawer-tree>
    <!--菜单分配弹窗-->
    <drawer-tree :drawer="menuDialog" :data="menuDrawer" :props="menuDrawerProps" treeRef="treeRef"
                 :default-checked-keys="menuTree" @treeBtn="menuBtn" :title="menuTitle">
    </drawer-tree>
    <!--对应角色的用户列表-->
    <el-drawer  v-model="roleUserdrawer" :with-header="false" size="50%">
        <table-list :page="roleUser" :columns="userColumns" :table-data="RoleUser" @click="selectionChange"
                     @pageChange="roleUserChange" @delete="delRoleUser"  @handleSelectChange="selectionChange"
                      @addBtn="aaa" @plDelete="deleteUserRole" :disabled="show">
        </table-list>
    </el-drawer>
  </div>
</template>

<script>
import PagePagination from "../../../components/PagePagination";
import TableList from "../../../components/tableList";
import Search from "../../../components/system/search";
import DrawerTree from "../../../components/system/drawerTree";
import DrawerList from "../../../components/system/drawerList";
export default {
  name: "Roles",
  components: {DrawerList, DrawerTree, Search, TableList, PagePagination},
  data(){
    return{
      //获取到的角色权限列表
      roleJurisdiction:[],//保存角色权限列表数据
      jurisdictionProps:{
        children:'children',
        label:'describes'
      },
//菜单分配
      menuTitle: '菜单分配',
      menuDrawer: [],//保存菜单列表数据
      menuDialog:false,
      menuDrawerProps:{
        children:'children',
        label:'name'
      },
      menuTree: [],//保存选中的菜单id
//----------------------------
      jurisdictionTitle: '角色权限列表',
      roleTree:[],//保存默认选中的勾选框的id
      jurisdictionDialog:false,//是否角色权限弹出框
      disable:false,//添加或修改弹框中的code是否能修改
      // 角色添加/修改表单规则
      roleForm:{
        code: '',
        name: '',
        discribe: ''
      },
      rules:{
        code: [
          {required: true, message: '请输入代码', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ]
      },
      roleDialogVisible: false,//是否添加\修改弹出框
  //----------------------------
      role: {
        code: '',
        name: '',
        discribe: '',
        pageNo: 1,
        pageSize: 10,
        pageNum: null,//请求过来的当前页数
        totalPage: null,//请求过来的总页数
        count: null,//请求过来的总条数
        roleCode: ''
      },
      rows: [
        {type: 'code', placeholder: '请输入角色代码'},
        {type: 'name', placeholder: '请输入姓名'},
      ],

      roleList: [],//保存角色列表数据
      columns: [
        {id: 'selection',  type: 'selection'},
        {id: 'index', label: '序号', type: 'index'},
        {id: 'code', prop: 'code', label: '角色编码'},
        {id: 'name', prop: 'name', label: '角色名称'},
        {id: 'createDate', prop: 'createDate', label: '创建时间'},
        {id: 'discribe', prop: 'discribe', label: '描述'},
        {id: 'button', label: '操作', type: 'button',list:[
            {id: 'edit', label: '修改', type: 'text'},
            {id: 'delete', label: '删除', type: 'text'},
            {id: 'roleUser', label: '用户', type: 'text'},
            {id: 'jurisdiction', label: '权限授权', type: 'text'},
            {id: 'menu', label: '角色菜单分配', type: 'text'},]},
      ],
//------------
      RoleUser: [],//查询对应角色的用户列表
      roleUserdrawer: false,
      name:'',//将当前用户名保存下来
      show: true,
      deleteRoleUser: [],//用于存放批量删除时的数据
      roleUser: {
        phone: '',
        nickname: '',
        realname: '',
        sex: '',
        count: null,
        pageNo: 1,
        pageSize: 5,
      },
      userRoleSearch:[
        {type:'phone',name:'phone' , placeholder: '请输入手机号' },
        {type:'nickname',name:'nickname' , placeholder: '请输入昵称' }
      ],
      userColumns: [
        {id: 'selection',  type: 'selection'},
        {id: 'index', label: '序号', type: 'index'},
        {id: 'phone', prop: 'phone', label: '手机号'},
        {id: 'nickname', prop: 'nickname', label: '昵称'},
        {id: 'realname', prop: 'realname', label: '姓名'},
        {id: 'sex', prop: 'sex', label: '性别'},
        {id: 'state', prop: 'state', label: '状态'},
        {id: 'button', label: '操作', type: 'button',list:[
            {id: 'edit', label: '编辑', type: 'text'},
            {id: 'delete', label: '删除', type: 'text'},]},
      ]
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    //添加当前角色的用户
    aaa() {
      console.log('添加用户')
    },

    //接收传过来的page改变
    pageChange(val) {
        this.role.pageNo = val.pageNo;
        this.role.pageSize = val.pageSize;
        this.getRoleList(this.role)
      },
    roleUserChange(val) {
      this.roleUser.pageNo = val.pageNo;
      this.roleUser.pageSize = val.pageSize;
      this.RoleUsers(this.name);
    },
    //获取角色列表
   async getRoleList() {
      const par = {
        code: this.role.code,
        name: this.role.name,
        pageNo: this.role.pageNo,
        pageSize: this.role.pageSize
      }
     await this.$api.system.getRole(par).then(res => {
        //console.log('这是角色列表：', res.data);
        this.roleList = res.data.data;

        this.role.count =  res.data.count;
        this.role.pageNum = res.data.pageNum;
        this.role.totalPage =  res.data.totalPage;
      })
    },
//重置按钮
    reset() {
      this.role = {};
      this.getRoleList()
    },
    //userRoleReset() {
    //  this.roleUser = {};
    //    this.RoleUsers(this.name);
    //},
    // 添加角色按钮事件
    addRole() {
      this.role = {};
      this.roleDialogVisible = true;
    },
    // 修改角色信息按钮事件
   async editRole(val){
     this.role.code=val.code
     this.disable=true;
      //console.log(this.role.code);
    await  this.$api.system.codeRoleSelect(this.role.code, this.roleForm).then(res=>{
        if(res.status == 200){
          this.roleForm=res.data.data
          this.roleDialogVisible=true;
          //console.log(this.roleForm);
        }else{
          this.$message.error('失败')
        }
      })
    },
    // 添加/修改角色信息的弹出框
    async  roleSumbit(formName) {
     await this.$refs[formName].validate((valid) => {
        if (valid) {
          const code = this.role.code;
          //console.log(code)
          if (code == null||code == '') {
            this.$api.system.addRole(this.roleForm).then(res => {
              if (res.data.code === 200){
                this.$message.success(res.data.message);
                this.getRoleList();
                this.roleDialogVisible = false;
              }else {
                this.$message.error('添加失败！！！角色可能已存在')
              }
            })
          }else {
            this.$api.system.editRole(this.roleForm).then(res => {
              // this.disable=true;
              if (res.data.code === 200) {
                this.$message.success('修改成功');
                this.role.code = null;
                this.getRoleList()
                this.roleDialogVisible = false;
              }else {
                this.$message.error('修改失败')
              }
            })
          }
        }else {
          return false
        }

      })
    },
    // 删除角色
  async  delRole(valid) {
     await this.$confirm('是否删除？','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       let par = valid.code;
          this.$api.system.deleteRole(par).then(res=>{
        if(res.data.code === 200){
            this.$message.success('删除成功')
            this.getRoleList()
          }else {
          this.$message.error('删除失败')
        }
        }).catch(err =>  this.$message.error(res.message))
      }).catch(err => {
        this.$message.error('取消删除操作')
      })
    },

//角色权限列表
   async jurisdiction(val){
      //   console.log('你点击了权限分配');
      this.roleTree = [];
      this.role.roleCode = val.code;
      const par = {
        roleCode:val.code
      }
     await this.$api.system.RoleJurisdiction(par).then(res=>{
        if (res.data.code === 200){
          //console.log(res.data.data);
          this.roleJurisdiction = res.data.data;
          //console.log('123123----',this.roleTree)
          this.common.methods.getTreeKey(this.roleJurisdiction, this.roleTree)
          //console.log('-=-=-====',this.roleTree)
          this.jurisdictionDialog = true
        }else{
          this.$message.error(res.data.message)
        }
      });

    },
    // 权限分配弹框中的确定按钮
    treeBtn(Arr){
      //console.log('treeArray', Arr);
      this.roleTree = Arr;
      var para={
        roleCode:this.role.roleCode,
        juriIds:this.roleTree.toString()
      };
      this.$api.system.getRoleAllocation(para).then(res=>{
        if (res.data.code===200){
          this.jurisdictionDialog = false;

        }
      });

    },

//角色菜单分配
    async jurisMenu(val) {
      //console.log(val)
      this.menuTree = [];
      this.role.roleCode = val.code
      var par = {
        category: 0,
        roleCode: this.role.roleCode
      }
       this.$api.system.RoleMenuJurisdiction(par).then(res => {
        if (res.data.code === 200) {
          this.menuDrawer = res.data.data;
          this.common.methods.getTreeKey(this.menuDrawer, this.menuTree);
        }else return this.$message.error('错误')
      this.menuDialog = true;
    }).catch(err => {
      this.$message.error('分配出错咯')
       })
    },
    async  menuBtn(Arr) {
        this.menuTree = Arr;
        var par = {
          roleCode: this.role.roleCode,
          category: 0,
          menuIds: this.menuTree.toString()
        }
      await this.$api.system.RoleMenu(par).then(res => {
        //console.log(res)
        if (res.status == 200){
          this.menuDialog = false;
        }
      })
    },


  //查看当前角色的用户
    RoleUsers(val) {
      if (!val.code){
        //console.log('name=',val)
        this.name = val
      }else {
        //console.log('name==',val.code)
        this.name = val.code
      }

    var par = {
      roleCode: this.name,
      pageNo: this.roleUser.pageNo,
      pageSize: this.roleUser.pageSize
    }
    this.$api.system.getRoleUser(par).then(res => {
        //console.log(res.data.data);
        this.RoleUser = res.data.data
      this.roleUser.count = res.data.count
      this.roleUserdrawer = true
      }
    ).catch()
    //console.log('查看当前角色的用户')
  },

    selectionChange(data) {
      if (data.length > 0) {
        this.show = false;
        let ids = [];
        for (let i=0;i < data.length;i++) {
          let item = data[i];
          ids.push(item.roleUserId);
        }
        this.deleteRoleUser = ids.join(',');
      }else this.show = true
    },
  //批量删除删除角色里的用户
  async deleteUserRole () {
    await this.$confirm('是否删除？','提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      let par = {ids: this.deleteRoleUser};
      this.$api.system.deleteRoleUser(par).then(res => {
        //console.log(res);
        if (res.data.code === 200) {
          this.$message.success('删除成功')
          this.RoleUsers(this.name)
        } else {
          this.$message.error('奇怪，删除失败！？')
        }
      }).catch(err => this.$message.error('删除失败咯！'));
    })
    .catch(() => {
      this.$message.error('取消删除')
    })
  },
    //单个删除角色里的用户
    delRoleUser(val) {
      console.log(val)
        this.deleteRoleUser = val.roleUserId;
      //console.log('单个的=', this.deleteRoleUser)
          this.deleteUserRole();
    },
  },
}
</script>

<style scoped>
.el-rowss{
  margin: 15px;
}
.el-rowss .el-col .el-input {
  margin: 10px;
}
.el-rowss .el-col .el-button {
  margin: 5px;
}
.el-header .el-row .el-button{
  clear: both;
}
 .el-table-column{
  text-align: center;
  margin: 5px;
}
.el-table-column button{
  width: 30px;
}
/*.el-drawer .el-form .el-button{*/
/*float: right;*/
/*  margin: 5px;*/
/*}*/
/*.el-drawer  .el-button{*/
/*  float: right;*/
/*  margin: 5px;*/
/*}*/

.el-pagination{
  float: right;
  margin-top: 5px;
  margin-bottom: 5px;
}
</style>